package com.tbm.console.proj.json;

import com.tbm.console.base.controller.BaseController;
import com.tbm.console.common.constant.ConsoleConstant;
import com.tbm.console.common.constant.Controller2FTLConstant;
import com.tbm.console.common.constant.InsUpdDelFlagConstant;
import com.tbm.console.common.constant.RedisKeyConstant;
import com.tbm.console.proj.entity.*;
import com.tbm.console.proj.service.*;
import com.tbm.console.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class SystemConfigDevelopJson extends BaseController {

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private TemplatePageService templatePageService;

    @Autowired
    private SystemMenuService systemMenuService;

    @Autowired
    private SystemRoleService systemRoleService;

    @Autowired
    private SystemButtonService systemButtonService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private LocalUserInfoService localUserInfoService;

    @Autowired
    private ColumnService columnService;

    /**
     * 显示list
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/config-list/{page}/{size}")
    public Map<String,Object> localConstantList(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        PageData pageData = this.getPageData();
        pageData.put("deleteFlag", "N");
        long count = systemConfigService.count(pageData);
        List<SystemConfig> systemConfigs = systemConfigService.findAll(pageData,page-1,size);
        pageData.put("total",count);
        pageData.put("rows", systemConfigs);
        return pageData;
    }

    /**
     * 常量增删改
     * @return
     */
    @RequestMapping(value = "/config-ins-upd-del")
    public Object logCreateUpdate(){
        PageData pageData = this.getPageData();
        Integer id = -1;

        if(null != pageData.get("id")&&!"".equals(pageData.get("id").toString())){
            id = Integer.valueOf(pageData.get("id").toString());
        }
        SystemConfig systemConfig = systemConfigService.findById(id);

        //------------------------------------------------------- 新增修改操作 ----------------------------------------------------------------------//
        //字段信息维护
        if(null!=pageData.get("entityName")&&!"".equals(pageData.get("entityName").toString())){
            systemConfig.setEntityName(pageData.get("entityName").toString());
            //本目录名称Rout
            systemConfig.setSelfMenuNameRout(StringsUtil.lowerCase(pageData.get("entityName").toString())+"-list");
        }
        //属性字段维护
        if(null!=pageData.get("entityAttribute")&&!"".equals(pageData.get("entityAttribute").toString())){
            systemConfig.setEntityAttribute(pageData.get("entityAttribute").toString());
        }
        //表名字段维护
        if(null!=pageData.get("tableName")&&!"".equals(pageData.get("tableName").toString())){
            systemConfig.setTableName(pageData.get("tableName").toString());
        }
        //此界面所对应的一级菜单
        if(null!=pageData.get("parentMenuNameKey")&&!"".equals(pageData.get("parentMenuNameKey").toString())){
            //此界面所对应的一级菜单
            Integer firstMenu = new Integer(0);
            //此界面所对应的二级菜单
            Integer secondMenu = new Integer(0);
            //如果是已有的，pageData.get("parentMenuNameKey")可以转成Integer,同时一级菜单不需要存入，只需存入二级菜单
            try {
                firstMenu = Integer.valueOf(pageData.get("parentMenuNameKey").toString());
                systemConfig.setParentMenuNameKey(String.valueOf(firstMenu));
            } catch (NumberFormatException e) {
                //如果是新增的，pageData.get("parentMenuNameKey")不可以转成Integer，需要存入一级菜单
                //新增parentMenu
                SystemMenu parentSystemMenu = new SystemMenu();
                parentSystemMenu.setMenuName(pageData.get("parentMenuNameKey").toString());
                parentSystemMenu.setMenuURL("#");
                parentSystemMenu.setMenuIcon("Hui-iconfont-news");
                parentSystemMenu.setParentId("0");
                systemMenuService.save(parentSystemMenu);
                firstMenu = parentSystemMenu.getId();
                systemConfig.setParentMenuNameKey(String.valueOf(firstMenu));
            }
                //新增selfMenu
            SystemMenu secondSystemMenu = new SystemMenu();
            secondSystemMenu.setMenuName(pageData.get("selfMenuNameValue").toString());
            secondSystemMenu.setMenuURL(StringsUtil.lowerCase(pageData.get("entityName").toString())+"-list");
            secondSystemMenu.setMenuIcon("#");
            secondSystemMenu.setParentId(String.valueOf(firstMenu));
            systemMenuService.save(secondSystemMenu);
            secondMenu = secondSystemMenu.getId();

            systemConfig.setParentMenuId(firstMenu);
            systemConfig.setSelfMenuId(secondMenu);
        }
        //本目录名称Value
        if(null!=pageData.get("selfMenuNameValue")&&!"".equals(pageData.get("selfMenuNameValue").toString())){
            systemConfig.setSelfMenuNameValue(pageData.get("selfMenuNameValue").toString());
        }

        //------------------------------------------------------- 删除操作 ---------------------------------------------------------------------------//
        if(null!=pageData.get("flag")&&"Y".equals(pageData.get("flag").toString())){
            systemConfig.setDeleteFlag(pageData.get("flag").toString());
        }
        systemConfigService.save(systemConfig);
        return null;
    }
    /**
     * 生成文件
     */
    @RequestMapping("/config-generate")
    public void adminDownload(){
        PageData pageData = this.getPageData();
        Object id = pageData.get("id");
        Object entityName = pageData.get("entityName");
        Object entityAttribute = pageData.get("entityAttribute");
        Object tableName = pageData.get("tableName");
        if((null!=entityName&&!"".equals(entityName.toString())&&(null!=entityAttribute&&!"".equals(entityAttribute.toString())))&&
                (null!=tableName&&!"".equals(tableName.toString()))){
            //实体名称
            String entityNameStr = entityName.toString();
            //属性
            String[] entityAttrSplit = entityAttribute.toString().split(";");
            String entityContent = "";
            for(int i=0;i<entityAttrSplit.length;i++){
                String temp = entityAttrSplit[i];
                String entityAttr = temp.split("_")[0];
                String entityAttrType = temp.split("_")[1];
                entityContent += "\r\n\tprivate "+entityAttrType+"  "+entityAttr+";\n";
            }
            //所有模板
            List<TemplatePage> allTemplatePage = templatePageService.findAll();
            //c从redis读取

            //留一个口子
            // stringRedisTemplate.opsForValue().get(RedisKeyConstant.USERINFOREDISKEY);
            //第一步：生成所有页面
            for(TemplatePage templatePage :allTemplatePage){
                String outPutFileName = "";
                //输出名称为：**-list.ftl
                if(templatePage.getTemplatePageName().equals("FTL")){
                    outPutFileName += StringsUtil.lowerCase(entityNameStr) + "-list.ftl";
                //输出名称：A*.java
                }else{
                    outPutFileName += entityNameStr + templatePage.getTemplatePageName() + ".java";
                }
                String templatePageContent = templatePage.getTemplatePageContent();
                String replace= templatePageContent.replaceAll("TEMPLAGEREPLACE", entityNameStr);
                replace = replace.replaceAll("LOWEREREPLACE", StringsUtil.lowerCase(entityNameStr));
                //TABLENAME,ATTRIBUTES主要是针对Entity
                replace = replace.replaceAll("TABLENAME", tableName.toString());
                replace = replace.replaceAll("ATTRIBUTES", entityContent);
                InputStream inputStream = new ByteArrayInputStream(replace.getBytes());
                try{
                    String path = Controller2FTLConstant.WINDOWPATH;
                    SystemUser systemUser = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(), SystemUser.class);
                    PageData param = new PageData();
                    param.put("userId", systemUser.getId());
                    List<LocalUserInfoEntity> all = localUserInfoService.findAll(param);
                    if(all.size()==1){
                        LocalUserInfoEntity localUserInfoEntity = all.get(0);
                        String developBasePath = localUserInfoEntity.getDevelopPath();
                        String developBaseFTLPath = localUserInfoEntity.getDevelopFTLPath();
                        if(outPutFileName.endsWith("ftl")){
                            File ftlFileDir = new File(developBaseFTLPath+StringsUtil.lowerCase(entityNameStr));
                            ftlFileDir.mkdir();
                            path = ftlFileDir.getPath();
                        }else if(outPutFileName.endsWith("Json.java")){
                            path = developBasePath + "" + Controller2FTLConstant.JSONPATH + "\\";
                        }else if(outPutFileName.endsWith("Controller.java")){
                            path = developBasePath + "" + Controller2FTLConstant.CONTROLLERPATH+ "\\";
                        }else if(outPutFileName.endsWith("Entity.java")){
                            path = developBasePath + "" + Controller2FTLConstant.ENTITYPATH + "\\";
                        }else if(outPutFileName.endsWith("Repository.java")){
                            path = developBasePath + "" + Controller2FTLConstant.REPOSITORYPATH + "\\";
                        }else if(outPutFileName.endsWith("Service.java")){
                            path = developBasePath + "" + Controller2FTLConstant.SERVICEPATH + "\\";
                        }else if(outPutFileName.endsWith("ServiceImpl.java")){
                            path = developBasePath + "" + Controller2FTLConstant.IMPLPATH + "\\";
                        }
                    }
                    FileUpload.copyFile(inputStream, path, outPutFileName);
                }catch (IOException e){
                }
            }
            //第二步：授权
            SystemConfig byId = systemConfigService.findById(Integer.valueOf(id.toString()));
            //获取菜单
            String rights = this.getRequest().getSession().getAttribute(ConsoleConstant.RIGHTS).toString();
            String roleId = this.getRequest().getSession().getAttribute(ConsoleConstant.ROLEID).toString();
            List<String> ids = new ArrayList<>();
            ids.add(String.valueOf(byId.getParentMenuId()));
            ids.add(String.valueOf(byId.getSelfMenuId()));
            for(int i=0;i<200;i++){
                if (RightsHelper.testRights(rights.substring(1), i)) {
                    ids.add(String.valueOf(i));
                }
            }
            String[] idArray = ids.toArray(new String[ids.size()]);
            String newRights = "R"+String.valueOf(RightsHelper.sumRights(idArray));

            //第三步：生成按钮
            //
            PageData btnByMenuId = new PageData();
            btnByMenuId.put("menuID", byId.getSelfMenuId());
            List<SystemButton> systemButtonList = systemButtonService.findAll(btnByMenuId);
            Integer systemAddButtonId = new Integer(0);
            Integer systemEditButtonId = new Integer(0);
            Integer systemDeleteButtonId = new Integer(0);
            Integer systemSaveButtonId = new Integer(0);
            if(systemButtonList.size()==0){
                //新增
                SystemButton systemAddButton = new SystemButton(byId.getSelfMenuId(),"新增","icon-add","新增业务","add");
                systemAddButton.setCreateTime(DateUtil.getID());
                systemButtonService.save(systemAddButton);
                systemAddButtonId = systemAddButton.getId();
                //修改
                SystemButton systemEditButton = new SystemButton(byId.getSelfMenuId(),"修改","icon-edit","修改业务","edit");
                systemEditButton.setCreateTime(DateUtil.getID());
                systemButtonService.save(systemEditButton);
                systemEditButtonId = systemEditButton.getId();
                //删除
                SystemButton systemDeleteButton = new SystemButton(byId.getSelfMenuId(),"删除","icon-remove","删除业务","delete");
                systemDeleteButton.setCreateTime(DateUtil.getID());
                systemButtonService.save(systemDeleteButton);
                systemDeleteButtonId = systemDeleteButton.getId();
                //保存
                SystemButton systemSaveButton = new SystemButton(byId.getSelfMenuId(),"保存","icon-save","保存业务","save");
                systemSaveButton.setCreateTime(DateUtil.getID());
                systemButtonService.save(systemSaveButton);
                systemSaveButtonId = systemSaveButton.getId();
            }else{
                for(SystemButton sb : systemButtonList){
                    if(sb.getButtonId().equals("add")){
                        systemAddButtonId = sb.getId();
                    }else if(sb.getButtonId().equals("edit")){
                        systemEditButtonId = sb.getId();
                    }else if(sb.getButtonId().equals("delete")){
                        systemDeleteButtonId = sb.getId();
                    }else{
                        systemSaveButtonId = sb.getId();
                    }
                }
            }
            String buttonRights = this.getRequest().getSession().getAttribute(ConsoleConstant.BUTTONRIGHTS).toString();
            List<String> btnIds = new ArrayList<>();
            btnIds.add(String.valueOf(systemAddButtonId+200));
            btnIds.add(String.valueOf(systemEditButtonId+200));
            btnIds.add(String.valueOf(systemDeleteButtonId+200));
            btnIds.add(String.valueOf(systemSaveButtonId+200));
            for(int i=200;i<2000;i++){
                if (RightsHelper.testRights(buttonRights.substring(1), i)) {
                    btnIds.add(String.valueOf(i));
                }
            }
            String[] btnIdsArray = btnIds.toArray(new String[btnIds.size()]);
            String newBtnRights = "B"+String.valueOf(RightsHelper.sumRights(btnIdsArray));

            SystemRole systemRole = systemRoleService.findById(Integer.valueOf(roleId));
            systemRole.setRights(newRights);
            systemRole.setBtnRights(newBtnRights);
            systemRole.setUpdateTime(DateUtil.getID());
            systemRoleService.save(systemRole);
        }
    }



    /**
     * 显示column
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/config-column-list/{page}/{size}")
    public Map<String,Object> configColumnList(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        PageData pageData = this.getPageData();
        pageData.put("deleteFlag", "N");
        long count = columnService.count(pageData);
        List<ColumnEntity> systemConfigs = columnService.findAll(pageData,page-1,size);
        pageData.put("total",count);
        pageData.put("rows", systemConfigs);
        return pageData;
    }

    @RequestMapping(value = "/column-save/{id}")
    public String columnSave(@PathVariable("id") String id){
        PageData pd = this.getPageData();
        ColumnEntity columnEntity = columnService.findById(Integer.valueOf(id));
        if(null!=pd.get("tableName")&&!"".equals(pd.getString("tableName"))){
            columnEntity.setTableName(pd.getString("tableName"));
        }
        if(null!=pd.get("className")&&!"".equals(pd.getString("className"))){
            columnEntity.setClassName(pd.getString("className"));
        }
        if(null!=pd.get("deleteFlag")&&!"".equals(pd.getString("deleteFlag"))){
            columnEntity.setDeleteFlag(pd.getString("deleteFlag"));
        }
        //表示新增
        if(-1==Integer.valueOf(id)){
            try {
                Class clazz = Class.forName(ConsoleConstant.ENTITY_BASE_PATH + pd.getString("className"));
                List<String> strings = EntityAttributeUtil.entityAttribute(clazz);
                String allName = "";
                for(String str :strings){
                    allName += str + " ";
                }
                columnEntity.setAllName(allName.trim());
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        columnService.save(columnEntity);
        return "success";
    }

    @RequestMapping(value = "/column-set-save/{id}")
    public String columnSetSave(@PathVariable("id") String id){
        PageData pd = this.getPageData();
        ColumnEntity columnEntity = columnService.findById(Integer.valueOf(id));
        String[] split = columnEntity.getAllName().split(" ");
        StringBuilder freezeColumnSB = new StringBuilder();
        StringBuilder hiddenColumnSB = new StringBuilder();
        for(int i=0;i<split.length;i++){
            //冻结列 on--表示不冻结
            if(null!=pd.get(split[i])&&!"".equals(pd.getString(split[i]))){
                if(pd.getString(split[i]).equals("on")){
                    freezeColumnSB.append(split[i]+" ");
                }
            }
            //是否显示 on--表示显示
            if(null!=pd.get(split[i]+"_display")&&!"".equals(pd.getString(split[i])+"_display")){
                //隐藏
                if(pd.getString(split[i]+"_display").equals("on")){
                    hiddenColumnSB.append(split[i]+" ");
                }
            }
        }
        columnEntity.setFreezeName(freezeColumnSB.toString().trim());
        columnEntity.setHiddenName(hiddenColumnSB.toString().trim());
        columnService.save(columnEntity);
        return "success";
    }
}
